package com.ruoyi.user.service;

import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.user.utils.AliyunUtils;
import com.ruoyi.user.utils.Secures;
import com.ruoyi.user.utils.SnowflakeIdGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

/**
 * @author: houyong
 * @date: 2025年11月14日 11:35
 */
@Service
public class SsmService {

    @Autowired
    private RedisService redisService;

    @Value("${sms.accessKeyId}")
    private String accessKeyId;
    /**
     * 验证码长度
     */
    @Value("${sms.accessKeySecret}")
    private String accessKeySecret;
    /**
     * 验证码过期时间。单位：分钟
     */
    @Value("${sms.codeExpires:15}")
    private int codeExpires = 15;

    @Value("${sms.templateCode}")
    private String templateCode;

    @Value("${sms.codeName:code}")
    private String codeName;
    @Value("${email.host}")
    private String host;
    @Value("${email.port}")
    private Integer port;
    @Value("${email.ssl:false}")
    private Boolean ssl;
    @Value("${email.timeout:5000}")
    private Integer timeout;
    @Value("${email.from}")
    private String from;
    @Value("${email.username}")
    private String username;
    @Value("${email.password}")
    private String password;

    /**
     * 发送手机短信验证码
     *
     * @param receiver 接收者手机号码
     * @return 返回消息ID，发送失败时返回null
     */
    public String sendMobileMessage(String receiver) {
        // 生成唯一消息ID
        SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator();
        String messageId = String.valueOf(idGenerator.nextId());

        // 生成6位随机数字验证码
        String code = Secures.randomNumeric(6);
        String signName = "万邦来华";

        // 调用阿里云短信服务发送短信
        String result = AliyunUtils.sendSms(accessKeyId,
                accessKeySecret,
                signName,
                templateCode,
                codeName, code, receiver);

        // 如果发送成功，将验证码存储到Redis中
        if (!StringUtils.isBlank(result)) {
            redisService.setHashValue(messageId, receiver, code, codeExpires, TimeUnit.MINUTES);
            return messageId;
        } else {
            return null;
        }
    }

    private String getTemplateByLanguage(String language) {
        switch (language) {
            case "zh":
                return "您的验证码是：${code}";
            case "ar":
                return "code رمز التحقق الخاص بك هو: ${code}";
            case "en":
                return "Your verification code is: ${code}";
            case "fr":
                return "Votre code de vérification est : ${code}";
            case "es":
                return "Tu código de verificación es: ${code}";
            case "id":
                return "Kode verifikasi Anda adalah: ${code}";
            default:
                return "Your verification code is: ${code}";
        }
    }

    /**
     * 发送邮件验证码
     *
     * @param to 收件人邮箱地址数组
     * @param language 邮件语言，默认中文(zh)，可选值：zh,ar,en,fr,es,id
     * @return 返回消息ID，用于后续验证
     */
    public String sendMail(String[] to,String language) {
        String subject = "邮件验证码";
        String code = Secures.randomNumeric(6);
        String template = getTemplateByLanguage(language);
        String text =  StringUtils.replace(template, "${code}", code);
        // 配置邮件发送器
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setHost(host);
        mailSender.setUsername(username);
        mailSender.setPassword(password);
        mailSender.setDefaultEncoding("UTF-8");
        mailSender.setPort(port != null ? port : JavaMailSenderImpl.DEFAULT_PORT);

        // 设置邮件服务器属性
        Properties prop = new Properties();
        prop.setProperty("mail.smtp.auth", "true");
        if (ssl) {
            prop.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        }
        if (timeout != null) {
            prop.setProperty("mail.smtp.timeout", timeout.toString());
        }
        mailSender.setJavaMailProperties(prop);

        MimeMessage msg = mailSender.createMimeMessage();
        try {
            SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator();
            String messageId = String.valueOf(idGenerator.nextId());

            // 构造并发送邮件
            MimeMessageHelper helper = new MimeMessageHelper(msg, true, "UTF-8");
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(text, false);
            mailSender.send(msg);

            // 将验证码存储到Redis中
            redisService.setHashValue(messageId, to[0], code, codeExpires, TimeUnit.MINUTES);
            return messageId;

        } catch (MessagingException e) {
            throw new IllegalStateException(e);
        }
    }


    /**
     * 验证验证码是否正确
     *
     * @param messageId    邮箱消息ID，用于定位Redis中的哈希表
     * @param hField       哈希表中的字段名
     * @param messageValue 待验证的邮箱消息值
     * @return 验证成功返回true，验证失败返回false
     */
    public boolean tryCode(String messageId, String hField, String messageValue) {
        // 从Redis中获取指定邮箱消息ID和字段对应的值
        String value = redisService.getHash(messageId, hField);
        // 比较获取到的值与传入的邮箱消息值是否相等
        return value.equals(messageValue);
    }

}
